import express from 'express'
import { Result} from '../config/Result.js'
import {logger} from '../utils/logger.js'

const router = express.Router()

/**
 * @apiDefine sse
 * SSE模块
 */

/**
 * @api {get} /sse/connect 链接SSE
 * @apiDescription 服务器推送事件流（SSE）
 * @apiVersion 1.0.0
 * @apiName sseConnect
 * @apiGroup sse
 * @apiHeader {String} Authorization token
 * @apiExample {js} SSE 客户端示例:
 * const eventSource = new EventSource('/sse/connect');
 * eventSource.onmessage = (e) => console.log(JSON.parse(e.data));
 * @apiUse sse
 */
router.get('/connect', (req, res) => {
	res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
	res.setHeader('Cache-Control', 'no-cache');
	res.setHeader('Connection', 'keep-alive');

	// 发送事件
	const sendEvent = () => {
		res.write(JSON.stringify(Result.success('Hello from server')));
	};

	// 每隔一定时间发送一次事件
	const intervalId = setInterval(sendEvent, 5000);

	// 当客户端关闭连接时清除定时器
	req.on('close', () => {
		logger.error('SSE关闭');
		clearInterval(intervalId);
		res.end();
	});
})

export default router
